package com.yzsj.socket.util;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

/**
 * @ClassName DateMyUtils
 * @Desscription TODO
 * @Author wjl
 * @Date 2019/8/13 17:08
 * @Version 1.0
 **/
public class DateMyUtils {

    /**
     * 时间格式(yyyy-MM-dd HH:mm:ss)
     */
    public final static String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";

    /**
     * 获取当年的开始时间戳
     *
     * @param timeStamp 秒级时间戳
     * @param timeZone  如 GMT+8:00
     * @return
     */
    public static Long getYearStartTime(Long timeStamp, String timeZone) {
        // 获取当前日期
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeZone(TimeZone.getTimeZone(timeZone));
        calendar.setTimeInMillis(timeStamp);
        calendar.add(Calendar.YEAR, 0);
        calendar.add(Calendar.DATE, 0);
        calendar.add(Calendar.MONTH, 0);
        calendar.set(Calendar.DAY_OF_YEAR, 1);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTimeInMillis() / 1000;
    }

    /**
     * 格式化日期yyyy-MM-dd HH:mm:ss
     *
     * @param dateTime
     * @return
     */
    public static Date getDateByYMDHMS(String dateTime) {
        DateFormat fmt = new SimpleDateFormat(DATE_TIME_PATTERN);
        Date date = new Date();
        try {
            date = fmt.parse(dateTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    /**
     * 获取月份
     *
     * @param date
     * @return
     */
    public static int getMonth(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        return cal.get(Calendar.MONTH) + 1;
    }

    /**
     * 获取月份
     *
     * @param dateTime
     * @return
     */
    public static int getMonth(String dateTime) {
        Date dateByYMDHMS = getDateByYMDHMS(dateTime);
        return getMonth(dateByYMDHMS);
    }
}
